package com.yitong.xjd.controller;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.yitong.xjd.domain.GuiZe;

public class XmlParseUtils {
	
	//解析xml文件，生产目标对象
	public static Element getRootDocumengt(String xmlStr) throws Exception {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
		Element root = document.getRootElement();
		return root;
	}
	
	//读取规则配置文件
	@SuppressWarnings("rawtypes")
	public static List<GuiZe> getRulesFromLocalXml(String filepath) throws DocumentException{
		List<GuiZe> rules1=new ArrayList<GuiZe>();
		SAXReader sr = new SAXReader();
		Document doc = sr.read(filepath);
		Element el_root = doc.getRootElement();
		for (Iterator iter = el_root.elementIterator(); iter.hasNext();) {
			Element e = (Element) iter.next();
			GuiZe g=new GuiZe();
			g.setName(e.element("name").getText().trim());
			g.setPath(e.element("path").getText().trim());
			g.setReg(e.element("reg").getText().trim());
			rules1.add(g);
		}
		return rules1;
	}
	
	
	//获取某条规则
	public static GuiZe getRuleByName(List<GuiZe>rules,String name){
		GuiZe gg=null;
		for(GuiZe g:rules){
			if(g.getName().equals(name)){
				gg=g;
			}
		}
		return gg;
	}
	
	
	//解析出某个类型的原始值
	public static Element getValueFromDocument(Element root,List<GuiZe> guizes,String name) {
		System.out.println("####################################################: "+name);
		Element e=null;
		GuiZe guize=getRuleByName(guizes,name);
		if(guize!=null&&!guize.getPath().equals("")){//按路径获取元素值
			e=getElement(root,guize.getPath());
		}
		return e;
	}

	
	//递归获取深处的元素（层数不定）
	public static Element getElement(Element e,String path){
		Element e1=null;
		if(path.indexOf("@")!=-1){//如果包含@字符
			int n=path.indexOf("@");
			String head=path.substring(0,n);
			String tail=path.substring(n+1);
			Element next = getCondElement(e, head);
			if(next!=null){
				e1=getElement(next,tail);
			}else{
				System.out.println("不存在head节点");
				return null;
			}
		}else{//如果不含@返回
			e1=getCondElement(e, path);
		}
		return e1;
	}

	//按配置文件找到某元素
	@SuppressWarnings("unchecked")
	public static Element getCondElement(Element e, String head) {
		System.out.println("*******"+e.getName()+":"+head);
		
		Element next=null;
		if(head.indexOf("_")!=-1){
			int m=head.indexOf("_");
			String ihead=head.substring(0,m);
			String cond=head.substring(m+1);
			List<Element> list= e.elements(ihead);
			
			if(cond.startsWith("first")){
				next=(Element) list.get(0);
			}else if(cond.startsWith("last")){
				next=(Element)list.get(list.size()-1);
			}else if(cond.startsWith("next")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(list.get(i).asXML().indexOf(content)!=-1){
						next=list.get(i+1);
					}
				}
			}else if(cond.startsWith("before")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(list.get(i).asXML().indexOf(content)!=-1){
						next=list.get(i-1);
					}
				}
			}else if(cond.startsWith("num")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String num=cond.substring(start+1,end);
				int n=Integer.parseInt(num);
				if(n>=0){
					next=list.get(n);
				}
			}else if(cond.startsWith("contain")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(list.get(i).asXML().indexOf(content)!=-1){
						next=list.get(i);
					}
				}
			}else if(cond.startsWith("like")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(ifRegExp(list.get(i).asXML(),content)){
						next=list.get(i);
					}
				}
			}else if(cond.startsWith("nlike")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(ifRegExp(list.get(i).asXML(),content)){
						next=list.get(i+1);
					}
				}
			}
		}else{
			next=e.element(head);
		}
		return next;
	}

	//按配置文件找到某元素
	@SuppressWarnings({ "unchecked" })
	public static List<Element> getCondElements(Element e, String head) {
		List<Element> targets = new ArrayList<Element>();
		
		if(head.indexOf("_")!=-1){
			int m=head.indexOf("_");
			String ihead=head.substring(0,m);
			String cond=head.substring(m+1);
			List<Element> list= e.elements(ihead);
			
			if(cond.startsWith("firsts")){//默认first为取从头开始的所有元素，firstN取前N个元素
				if(cond.equals("firsts")){
					for(int i=0;i<list.size();i++){
						targets.add(list.get(i));
					}
				}else{
					String num=cond.substring(cond.lastIndexOf("s")+1);
					int cnt=Integer.parseInt(num);
					for(int i=0;i<list.size();i++){
						if(cnt!=0){
							targets.add(list.get(i));
							cnt-=1;
						}
					}
				}
			}else if(cond.startsWith("lasts")){//默认last为取从尾部开始的所有元素，LastN取尾部N个元素
				if(cond.equals("lasts")){
					for(int i=list.size()-1;i>0;i--){
						targets.add(list.get(i));
					}
				}else{
					String num=cond.substring(cond.lastIndexOf("s")+1);
					int cnt=Integer.parseInt(num);
					for(int i=list.size()-1;i>0;i--){
						if(cnt!=0){
							targets.add(list.get(i));
							cnt-=1;
						}
					}
				}
			}else if(cond.startsWith("nexts")){//tr_next(condition) next之后的所有，tr_next3(condition)next之后的3个
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String count=cond.substring(0,start);
				if(count.equals("nexts")){
					int n=-1;
					String content=cond.substring(start+1,end);
					for(int i=0;i<list.size();i++){
						if(n!=-1){
							targets.add(list.get(i));
						}
						if(list.get(i).asXML().indexOf(content)!=-1){
							n=0;
						}
					}
				}else{
					String num=cond.substring(5,start);
					int cnt=Integer.parseInt(num);
					int n=-1;
					String content=cond.substring(start+1,end);
					for(int i=0;i<list.size();i++){
						if(n!=-1&&cnt!=0){
							targets.add(list.get(i));
							cnt-=1;
						}
						if(list.get(i).asXML().indexOf(content)!=-1){
							n=0;
						}
					}
				}
			}else if(cond.startsWith("befores")){//tr_before(condition) before之前的所有，tr_before3(condition)before之前的3个
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String count=cond.substring(0,start);
				if(count.equals("befores")){
					int n=-1;
					String content=cond.substring(start+1,end);
					for(int i=list.size()-1;i>0;i--){
						if(n!=-1){
							targets.add(list.get(i));
						}
						if(list.get(i).asXML().indexOf(content)!=-1){
							n=0;
						}
					}
				}else{
					String num=cond.substring(7,start);
					int cnt=Integer.parseInt(num);
					int n=-1;
					String content=cond.substring(start+1,end);
					for(int i=list.size()-1;i>0;i--){
						if(n!=-1&&cnt!=0){
							targets.add(list.get(i));
							cnt-=1;
						}
						if(list.get(i).asXML().indexOf(content)!=-1){
							n=0;
						}
					}
				}
			}else if(cond.startsWith("nums")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String[] nums=cond.substring(start+1,end).split(",");
				for(int i=0;i<list.size();i++){
					if(inNums(i+"",nums)){
						targets.add(list.get(i));
					}
				}
			}else if(cond.startsWith("contains")){
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(list.get(i).asXML().indexOf(content)!=-1){
						targets.add(list.get(i));
					}
				}
			}else if(cond.startsWith("likes")){//匹配某正则表达式
				int start=cond.indexOf("(");
				int end=cond.indexOf(")");
				String content=cond.substring(start+1,end);
				for(int i=0;i<list.size();i++){
					if(ifRegExp(list.get(i).asXML(),content)){
						targets.add(list.get(i));
					}
				}
			}
		}
		return targets;
	}
	private static boolean inNums(String str, String[] nums) {
		for(String s:nums){
			if(str.equals(s.trim())){
				return true;
			}
		}
		return false;
	}
	private static boolean ifRegExp(String asXML, String content) {
		Pattern p=Pattern.compile(content);
		Matcher m=p.matcher(asXML);
		while(m.find()){
			return true;
		}
		return false;
	}


	public static void main(String[] args) throws Exception {
		//读取资源文件
		String sPath=XmlParseUtils.class.getResource("").getPath();
		String sourcePath=sPath.substring(0, sPath.lastIndexOf("/utils"))+"/domain/daikuan/个人征信报告.xml";
		System.out.println("sourcePath: "+sourcePath);
		SAXReader sr = new SAXReader();
		Document doc = sr.read(sourcePath);
		Element root=doc.getRootElement();
		//读取xml字符串
		//Element root1=getRootDocumengt("");
		
		//读取规则
		String gzPath=XmlParseUtils.class.getResource("").getPath();
		String guizePath=gzPath.substring(0, gzPath.lastIndexOf("/domain"))+"/daikuan/xmlguize.xml";
		System.out.println("guizePath: "+guizePath);
		List<GuiZe> guizes=getRulesFromLocalXml(guizePath);
		
		//获取指定名称的值
		Element targetElement=getValueFromDocument(root,guizes,"custRegistAdd");
		System.out.println((targetElement==null)?"null":targetElement.getTextTrim());
		
	}
}